<?php
/**
 * 前台登录 退出操作
 *
 *
 *
 *
 * @copyright  Copyright (c) 2007-2013 ShopNC Inc. (http://www.BesonIT.net)
 * @license    http://www.BesonIT.net
 * @link       http://www.BesonIT.net
 * @since      File available since Release v1.1
 */


defined('BYshopJL') or exit('Access Invalid!');

class loginControl extends wxHomeControl
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 登录
     */
    public function indexOp()
    {
        if (empty($_POST['username']) || empty($_POST['password']) || !in_array($_POST['client'], $this->client_type_array)) {
            output_error('登录失败');
        }

        /* @var wx_memberModel $model_member */
        $model_member = Model('wx_member');

        $array = array();
        $array['member_name'] = $_POST['username'];
        $array['member_passwd'] = md5($_POST['password']);
        $member_info = $model_member->getMemberInfo($array);

        if (!empty($member_info)) {
            $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_POST['client']);
            if ($token) {
                output_data(array('username' => $member_info['member_name'], 'key' => $token));
            } else {
                output_error('登录失败');
            }
        } else {
            output_error('用户名密码错误');
        }
    }

    /**
     * 登录
     */
    public function wx_loginOp()
    {
        //生产模式，进行微信授权
        $model_member = Model('wx_member');
        if (!isset($_SESSION['is_login']) || $_SESSION['is_login'] != 1) {//未登录

            /*if (isset($_GET['login_redirect_url']) && !empty($_GET['login_redirect_url']) && !isset($_SESSION['login_redirect_url'])) {
                //var_dump($_GET);
                $_SESSION['login_redirect_url'] = $_GET['login_redirect_url'];
            }*/

            if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false && ENV == 'dev') {
                $result = array(
                    'access_token' => 'skdfhkasdjeirupeowrupsjfsdf',
                    'expires_in' => '7200',
                    'refresh_token' => 'fksadjfaasdfasdf',
                    'openid' => 'sdoiueofklfdjaskljpao',
                    'scope' => 'snsapi_base'
                );
            } else {
                //$wx = new weixin();
                $wx = new wxSdk();
                if (!isset($_GET['code'])) {
                    /*
                     * 微信授权第一步，获取code
                     * 下面代码不会执行，
                     */
                    $wx->webAuthGetCode();
                }
                /*
                 * 第二步
                 * 微信授权 获取用户信息
                 * ajax error 页面跳转回来执行下面
                 */
//                    $result = $wx->webAuthGetAccessToken();
//                    if (isset($result['errcode'])){
//                        output_error('用户名密码错误');//showMessage('Code无效');
//                    }
                $result = $wx->getOauthAccessToken();
                if (isset($result['errcode'])) {
                    output_error('用户名密码错误');//showMessage('Code无效');
                }

            }
            /* @var wx_memberModel $model_member */
            $model_member = Model('wx_member');
            //会员注册及登陆
            $model_member->register($result);

        }
        //var_dump($_SESSION);
        //var_dump($_SERVER);
        //var_dump($_COOKIE);

        //var_dump($_GET);
        if (isset($_GET['login_redirect_url'])) {
            if (!empty($_GET['login_redirect_url'])) {
                $url = urldecode($_GET['login_redirect_url']);
            } else {
                $url = '/wx';
            }

            //var_dump($url);
            //die(var_dump($_GET));

            header('Location:' . urldecode($url));
            exit;

        }
        /*
         * 第三步
         * 获取用户信息成功，生成对应session后,下面客户端验证并生成对应cookie 的 token
         */
        if (isset($_SESSION['member_wxopenid']) && !empty($_SESSION['member_wxopenid'])) {

            $member_info = $model_member->getMemberInfo(array('member_name' => $_SESSION['member_name']));
            //var_dump($member_info);
            $member_info['memberName'] = $member_info['member_name'];
            $member_info['member_name'] = strpos($member_info['member_name'], '__wx__') === 0 ? '微信用户' : $member_info['member_name'];
            if (!empty($member_info)) {
                $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], 'weixin');//$_POST['client']


                //var_dump($token);

                //绑定手机
                if ($member_info['member_mobile_bind'] == 1) $mobile_bind = 1;
                if ($token) {
                    output_data(array('username' => $member_info['member_name'], 'key' => $token, 'share' => $member_info['share_sign'], 'mobile_bind' => $mobile_bind,'memberName'=>$member_info['memberName']));
                } else {
                    output_error('登录失败');
                }
            } else {
                output_error('用户名密码错误');
            }
        }
        output_error('用户名密码错误');
    }

    /**
     * 登录生成token
     */
    private function _get_token($member_id, $member_name, $client)
    {
        $model_mb_user_token = Model('mb_user_token');

        //重新登录后以前的令牌失效
        //暂时停用
        //$condition = array();
        //$condition['member_id'] = $member_id;
        //$condition['client_type'] = $_POST['client'];
        //$model_mb_user_token->delMbUserToken($condition);

        //生成新的token
        $mb_user_token_info = array();
        $token = md5($member_name . strval(TIMESTAMP) . strval(rand(0, 999999)));
        $mb_user_token_info['member_id'] = $member_id;
        $mb_user_token_info['member_name'] = $member_name;
        $mb_user_token_info['token'] = $token;
        $mb_user_token_info['login_time'] = TIMESTAMP;
        $mb_user_token_info['client_type'] = $client;
        $result = $model_mb_user_token->addMbUserToken($mb_user_token_info);

        if ($result) {
            return $token;
        } else {
            return null;
        }

    }

    /**
     * 注册
     */
    public function registerOp()
    {
        $model_member = Model('wx_member');

        $register_info = array();
        $register_info['username'] = $_POST['username'];
        $register_info['password'] = $_POST['password'];
        $register_info['password_confirm'] = $_POST['password_confirm'];
        $register_info['email'] = $_POST['email'];
        $member_info = $model_member->register($register_info);
        if (!isset($member_info['error'])) {
            $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_POST['client']);
            if ($token) {
                output_data(array('username' => $member_info['member_name'], 'key' => $token));
            } else {
                output_error('注册失败');
            }
        } else {
            output_error($member_info['error']);
        }

    }

    /**
     * 查看登录状态
     * Author: walkskyer
     * Email:zwj_work@qq.com
     */
    public function statusOp()
    {
        //生产模式，进行微信授权
        if ($_SESSION['is_login'] != 1) {//未登录
            $wx = new weixin();
            if (!isset($_GET['code'])) $wx->webAuthGetCode();
            $result = $wx->webAuthGetAccessToken();
            if (isset($result['errcode'])) showMessage('Code无效');
            $member = Model('wx_member', BASE_PATH);
            //会员注册及登陆
            $member->register($result);
        }
    }

    public function loginStatusOp()
    {
        if ($_SESSION['member_id']) {
            $return = array('status' => 1);
        } else {
            $return = array('status' => 2);
        }
        output_data($return);
    }
}
